package com.shop.vuedemo.model.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.shop.vuedemo.exception.BaseErrorType;
import com.shop.vuedemo.exception.ErrorType;
import com.shop.vuedemo.exception.SysErrorType;
import lombok.Getter;

import java.time.Instant;
import java.time.ZonedDateTime;

/**
 * projectName: vueDemo
 * create on 2021/11/14 10:22
 *
 * @author yanbl
 * @Description :
 */
@Getter
public class Result<T> {

    public static final String SUCCESSFUL_CODE = "000000";
    public static final String SUCCESSFUL_MESG = "处理成功";

    private T data;
    private String message;
    private String code;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Instant time;

    public Result() {
        this.time = ZonedDateTime.now().toInstant();
    }

    public Result(T data) {
        this.data = data;
    }

    public Result(ErrorType errorType) {
        this.code = errorType.getCode();
        this.message = errorType.getMessage();
        this.time = ZonedDateTime.now().toInstant();
    }

    public Result(ErrorType errorType,T data) {
        this.data = data;
        this.code = errorType.getCode();
        this.message = errorType.getMessage();
        this.time = ZonedDateTime.now().toInstant();
    }

    public Result(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.time = ZonedDateTime.now().toInstant();
        this.data = data;
    }

    public static Result success(Object data) {
        return new Result<>(SUCCESSFUL_CODE,SUCCESSFUL_MESG,data);
    }

    public static Result success() {
        return success(null);
    }

    /**
     * 默认系统异常
     *
     * @return
     */
    public static Result fail() {
        return new Result<>(SysErrorType.SYSTEM_ERROR);
    }

    /**
     * 系统类异常并返回数据
     *
     * @param data
     * @return
     */
    public static Result fail(Object data) {
        return new Result<>(SysErrorType.SYSTEM_ERROR, data);
    }

    /**
     * 系统类异常并返回结果数据
     *
     * @param errorType
     * @param data
     * @return
     */
    public static Result fail(ErrorType errorType, Object data) {
        return new Result<>(errorType,data);
    }

    public static Result fail(ErrorType errorType) {
        return fail(errorType,null);
    }

    /**
     * 系统类异常返回数据
     *
     * @param baseErrorType
     * @param data
     * @return
     */
    public static Result fail(BaseErrorType baseErrorType, Object data) {
        return new Result<>(baseErrorType.getErrorType(),data);
    }

    /**
     * 系统类异常没有返回数据
     *
     * @param baseErrorType
     * @return
     */
    public static Result fail(BaseErrorType baseErrorType) {
        return fail(baseErrorType,null);
    }

    public boolean isSuccess() {
        return SUCCESSFUL_CODE.equals(this.code);
    }

    public boolean isFail() {
        return !isSuccess();
    }




}
